<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="问诊ID" prop="id">
        <el-input v-model="queryParams.id" placeholder="请输入问诊ID" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['manage:patientsConsultation:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['manage:patientsConsultation:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['manage:patientsConsultation:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['manage:patientsConsultation:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="patientsConsultationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="问诊ID" align="center" prop="id" />
      <el-table-column label="就诊人ID" align="center" prop="patientsId" />
      <el-table-column label="医生就诊记录ID" align="center" prop="doctorConsultationId" />
      <el-table-column label="用户ID" align="center" prop="userId" />
      <el-table-column label="病情描述" align="center" prop="chiefComplaint" />
      <el-table-column label="病情相关图片" align="center">
        <template #default="scope">
          <div class="media-cell">
            <img v-if="scope.row.supplementaryMedia" :src="scope.row.supplementaryMedia" alt="图片" class="preview-image"
              @click="handleImageClick(scope.row.supplementaryMedia)">
            <span v-else>无</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleDetail(scope.row)">
            查看详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:patientsConsultation:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['manage:patientsConsultation:remove']">删除</el-button>
          <el-button link type="danger" icon="Close" @click="handleCancelConsultation(scope.row)">
            取消问诊</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改在线问诊对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="patientsConsultationRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="就诊人" prop="patientsId">
          <el-input v-model="form.patientsName" placeholder="请选择就诊人" style="width: 70%;" readonly />
          <el-button type="primary" @click="openPatientSelectDialog" slot="append" style="width: 30;">选择就诊人</el-button>
          <!-- 新增一个隐藏的输入框用于存储就诊人 ID -->
          <el-input v-model="form.patientsId" type="hidden" />
        </el-form-item>
        <el-form-item label="病情描述" prop="chiefComplaint">
          <el-input v-model="form.chiefComplaint" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="病情相关图片" prop="supplementaryMedia">
          <image-upload v-model="form.supplementaryMedia" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 选择就诊人对话框 -->
    <el-dialog :title="选择就诊人" v-model="patientSelectDialogVisible" width="500px" append-to-body>
      <el-table :data="patientsList" @row-click="selectPatient" style="width: 100%;" stripe>
        <!-- <el-table-column prop="id" label="就诊人 ID"></el-table-column> -->
        <el-table-column prop="name" label="就诊人姓名" align="center"></el-table-column>
        <el-table-column prop="idNumber" label="身份证号" align="center"></el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="patientSelectDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 查看详情对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="50%">
      <el-form :model="detailForm" label-width="120px">
        <el-form-item label="就诊医生">
          <el-input v-model="detailForm.doctorId" readonly></el-input>
        </el-form-item>
        <el-form-item label="病情分析">
          <el-input v-model="detailForm.diagnosis" readonly></el-input>
        </el-form-item>
        <el-form-item label="治疗方案">
          <el-input v-model="detailForm.treatmentPlan" readonly></el-input>
        </el-form-item>
        <el-form-item label="建议药品">
          <el-table :data="drugList">
            <el-table-column label="药品名称" prop="drugName"></el-table-column>
            <el-table-column label="功能主治" prop="functionIndications"></el-table-column>
            <el-table-column label="用法用量" prop="usageAndDosage"></el-table-column>
            <el-table-column label="药品单价" prop="unitPrice"></el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="生活建议">
          <el-input v-model="detailForm.lifestyleAdvice" readonly></el-input>
        </el-form-item>
        <el-form-item v-if="detailForm.consultationStatus === 2" label="需要补充以下信息">
          <el-input v-model="detailForm.additionalInformationNeeded" readonly></el-input>
        </el-form-item>
        <el-form-item label="问诊状态">
          <!-- 直接绑定 detailForm 中的状态值 -->
          <dict-tag :options="consultation_status" :value="detailForm.consultationStatus" />
        </el-form-item>
        <el-form-item label="就诊时间">
          <el-input v-model="detailForm.consultationTime" readonly></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button v-if="detailForm.consultationStatus === 2" type="primary" @click="handleInfoSubmitted">
            我已补充资料
          </el-button>
          <el-button v-if="detailForm.consultationStatus === 4" type="warning" @click="showPaymentDialog = true">
            去付款
          </el-button>
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 新增图片弹窗 -->
    <el-dialog v-model="showImageModal" title="查看大图" width="60%">
      <img :src="selectedImageUrl" alt="大图预览" style="width: 100%; max-height: 70vh;">
    </el-dialog>
    <el-dialog v-model="showPaymentDialog" title="请付款" width="30%">
      <div style="text-align: center; margin-bottom: 20px;">
        请付款，一共 {{ totalPrice }} 元
      </div>
      <img src="@/assets/images/shoukuan.png" alt="付款二维码" style="width: 100%; max-height: 70vh;">
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showPaymentDialog = false">已完成付款</el-button>
          <el-button @click="showPaymentDialog = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PatientsConsultation">
import { listPatientsConsultation, getPatientsConsultation, delPatientsConsultation, addPatientsConsultation, updatePatientsConsultation } from "@/api/manage/patientsConsultation";
import { listPatients } from "@/api/manage/patients";
import { getInfo } from "@/api/login";
import { getDoctorConsultation, updateDoctorConsultation } from "@/api/manage/doctorConsultation";
import { ElMessageBox } from 'element-plus';
import { getDrugs } from "@/api/manage/drugs";

const { proxy } = getCurrentInstance();

const patientsConsultationList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const patientSelectDialogVisible = ref(false);
const patientsList = ref([]);
const currentUserId = ref(null); // 用于存储当前登录用户的 ID
const dialogVisible = ref(false);
const dialogTitle = ref('详情');
const showImageModal = ref(false);
const selectedImageUrl = ref('');
const { consultation_status } = proxy.useDict('consultation_status');
const drugList = ref([]);
const showPaymentDialog = ref(false);

const detailForm = reactive({
  id: '',
  patientsConsultationId: '',
  doctorId: '',
  diagnosis: '',
  treatmentPlan: '',
  drugInfo: '', // 新增用于存储药品信息的字段
  lifestyleAdvice: '',
  additionalInformationNeeded: '',
  consultationStatus: '',
  consultationTime: ''
});

const data = reactive({
  form: {
    patientsId: null,
    patientsName: '',
    patientsId: null,
    chiefComplaint: null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: null,
    patientsId: null,
    doctorConsultationId: null,
    userId: null,
    createTime: null,
    updateTime: null
  },
  rules: {
    patientsId: [
      { required: true, message: "就诊人不能为空", trigger: "blur" }
    ],
    chiefComplaint: [
      { required: true, message: "病情描述不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询在线问诊列表 */
function getList() {
  loading.value = true;
  listPatientsConsultation(queryParams.value).then(response => {
    patientsConsultationList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    patientsId: null,
    chiefComplaint: null,
    supplementaryMedia: null,
    createTime: null,
    updateTime: null
  };
  proxy.resetForm("patientsConsultationRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加在线问诊";
}

// 查看问诊详细信息
async function handleDetail(row) {
  // 使用 getDoctorConsultation 函数根据 doctorConsultationId 获取详细信息
  const response = await getDoctorConsultation(row.doctorConsultationId);
  if (response && response.data) {
    // 提取 response.data 到一个变量中，避免重复访问
    const data = response.data;
    detailForm.id = data.id;
    detailForm.patientsConsultationId = data.patientsConsultationId;
    detailForm.doctorId = data.doctorId;
    detailForm.diagnosis = data.diagnosis;
    detailForm.treatmentPlan = data.treatmentPlan;
    detailForm.drugInfo = data.drugId;
    detailForm.lifestyleAdvice = data.lifestyleAdvice;
    detailForm.additionalInformationNeeded = data.additionalInformationNeeded;
    detailForm.consultationStatus = data.consultationStatus;
    console.log(detailForm.consultationStatus);
    if (detailForm.doctorId != null && detailForm.doctorId != '') {
      detailForm.consultationTime = response.data.updateTime;
    }

    // 根据药品 ID 获取药品详细信息
    if (detailForm.drugInfo) {
      const drugIds = detailForm.drugInfo.split(',');
      const newDrugList = [];

      // 循环调用 getDrugs 接口获取每个药品的信息
      for (const drugId of drugIds) {
        const drugResponse = await getDrugs(drugId);
        if (drugResponse && drugResponse.data) {
          newDrugList.push({
            drugName: drugResponse.data.drugName,
            functionIndications: drugResponse.data.functionIndications,
            usageAndDosage: drugResponse.data.usageAndDosage,
            unitPrice: drugResponse.data.unitPrice
          });
        }
      }

      drugList.value = newDrugList;
    } else {
      drugList.value = [];
    }
  }
  dialogVisible.value = true; // 显示对话框
}

// 用户确认已经补充资料
const handleInfoSubmitted = async () => {
  try {
    // 弹出确认框
    await ElMessageBox.confirm('确认已补充资料？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    // 创建一个新对象，将 consultationStatus 修改为 3
    const updatedForm = { ...detailForm, consultationStatus: 3 };
    console.log('更新请求参数:', updatedForm); // 打印参数

    // 调用更新接口同步数据库
    const response = await updateDoctorConsultation(updatedForm);
    console.log('更新接口响应:', response);

    // 检查更新是否成功
    if (response && response.code === 200) { // 假设后端返回的成功状态码是 200
      // 更新本地的 detailForm
      Object.assign(detailForm, updatedForm);
      dialogVisible.value = false; // 关闭对话框
      proxy.$modal.msgSuccess("资料补充状态已更新");
    } else {
      console.error('更新数据库失败:', response);
      proxy.$modal.msgError("更新数据库失败，请稍后重试");
    }
  } catch (error) {
    console.error('操作取消或出错:', error);
    proxy.$modal.msgError("操作取消或出错");
  }
};

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  try {
    const response = await getPatientsConsultation(_id);
    form.value = response.data;

    // 根据 patientsId 查询就诊人姓名
    if (form.value.patientsId) {
      const query = {
        pageNum: 1,
        pageSize: 1,
        id: form.value.patientsId
      };
      const patientResponse = await listPatients(query);
      if (patientResponse.rows.length > 0) {
        form.value.patientsName = patientResponse.rows[0].name; // 假设就诊人姓名的字段名为 name
      }
    }

    open.value = true;
    title.value = "修改在线问诊";
  } catch (error) {
    console.error('获取问诊信息失败:', error);
  }
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["patientsConsultationRef"].validate(valid => {
    if (valid) {
      console.log('fdffedrfrf', form.value);
      if (form.value.id != null) {
        updatePatientsConsultation(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addPatientsConsultation(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除在线问诊编号为"' + _ids + '"的数据项？').then(function () {
    return delPatientsConsultation(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

// 取消问诊操作
const handleCancelConsultation = async (row) => {
  try {
    // 弹出确认框
    await ElMessageBox.confirm('确认要取消此次问诊吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    // 构建要更新的数据对象，确保包含正确的表字段和 ID
    const updateData = {
      id: row.doctorConsultationId, // 假设关联的医生就诊记录 ID 是 doctorConsultationId
      consultationStatus: 6
    };

    // 调用更新接口同步数据库
    const response = await updateDoctorConsultation(updateData);
    console.log('更新接口响应:', response);

    // 检查更新是否成功
    if (response && response.code === 200) { // 假设后端返回的成功状态码是 200
      // 找到列表中对应的项并更新
      const index = patientsConsultationList.value.findIndex(item => item.id === row.id);
      if (index !== -1) {
        patientsConsultationList.value[index].consultationStatus = 6;
      }

      proxy.$modal.msgSuccess("问诊已取消");
    } else {
      console.error('更新数据库失败:', response);
      proxy.$modal.msgError("更新数据库失败，请稍后重试");
    }
  } catch (error) {
    console.error('操作取消或出错:', error);
    proxy.$modal.msgError("操作取消或出错");
  }
};


/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/patientsConsultation/export', {
    ...queryParams.value
  }, `patientsConsultation_${new Date().getTime()}.xlsx`)
}

// 打开就诊人选择对话框
async function openPatientSelectDialog() {
  if (!currentUserId.value) {
    console.error('未获取到当前登录用户的 ID');
    return;
  }
  try {
    const query = {
      pageNum: 1,
      pageSize: 100, // 假设查询足够多的就诊人，可根据实际情况调整
      userId: currentUserId.value
    };
    const response = await listPatients(query);
    patientsList.value = response.rows;
    patientSelectDialogVisible.value = true;
  } catch (error) {
    console.error('查询就诊人列表失败:', error);
  }
}

// 处理图片点击事件
const handleImageClick = (url) => {
  if (url) {
    selectedImageUrl.value = url;
    showImageModal.value = true;
  }
};


// 在组件挂载时获取当前登录用户的 ID
onMounted(async () => {
  try {
    const response = await getInfo();
    console.log('当前登录用户的 ID:', response);
    if (response.code === 200) {
      currentUserId.value = response.user.userId;
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
  }
});

// 选择就诊人
function selectPatient(row) {
  // 记录就诊人 ID
  form.value.patientsId = row.id;
  // 记录就诊人姓名
  form.value.patientsName = row.name;
  patientSelectDialogVisible.value = false;
}

const totalPrice = computed(() => {
  return drugList.value.reduce((sum, drug) => {
    return sum + (Number(drug.unitPrice) || 0);
  }, 0);
});

getList();
</script>

<style scoped>
/* 预览图片样式 */
.preview-image {
  max-width: 100px;
  /* 限制图片最大宽度 */
  max-height: 100px;
  /* 限制图片最大高度 */
  cursor: pointer;
  /* 鼠标悬停时显示手形指针 */
  transition: transform 0.2s;
  /* 添加缩放动画效果 */
}

/* 鼠标悬停时轻微放大图片 */
.preview-image:hover {
  transform: scale(1.05);
  /* 缩放比例为1.05倍 */
}
</style>